<template>
	<view class="container">
		<!-- 顶部搜索框 -->
		<uni-search-bar 
			v-model="searchPlate" 
			:placeholder="'输入车牌号码'"
			@search="onSearch"
			@confirm="onSearch"
			cancelButton="none"
			bgColor="#F5F0E6"
			radius="12"
		/>

		<!-- 三期名片显示区 -->
		<view class="card-section">
			<view class="card-container">
				<!-- 三期名片标题 -->
				<view class="card-title-header">
					<uni-icons type="card" size="24" color="#2A7A72"></uni-icons>
					<text class="card-main-title">三期名片</text>
				</view>

				<!-- 三期可办日期 -->
				<view class="service-dates-rows">
					<view class="date-row">
						<view class="date-type-tag insurance">保险可办期</view>
						<text class="date-value" :class="{ active: isInsuranceInTodoTime }">
							{{ getInsuranceTodoRange() }}
						</text>
					</view>
					<view class="date-row">
						<view class="date-type-tag maintenance">保养可办期</view>
						<text class="date-value" :class="{ active: isMaintenanceInTodoTime }">
							{{ getMaintenanceTodoRange() }}
						</text>
					</view>
					<view class="date-row">
						<view class="date-type-tag inspection">车检可办期</view>
						<text class="date-value" :class="{ active: isInspectionInTodoTime }">
							{{ getInspectionTodoRange() }}
						</text>
					</view>
					<!-- 车管家信息行 -->
					<view class="date-row">
						<view class="date-type-tag butler">车管家</view>
						<view class="butler-info-content">
							<view class="butler-right-section">
								<text v-if="butlerName" class="butler-name">{{ butlerName }}</text>
								<button 
									v-if="butlerMobile" 
									class="contact-btn-compact" 
									@click="callButler"
								>
									<uni-icons type="phone" size="12" color="#FFFFFF"></uni-icons>
									<text class="contact-text">联系</text>
								</button>
								<button 
									v-if="!searchResult || !searchResult.butler_id"
									class="select-butler-btn-compact" 
									@click="selectButler"
								>
									选车管家
								</button>
							</view>
						</view>
					</view>
				</view>

				<!-- 按钮区 - 一行四个按钮 -->
				<view class="action-buttons-row">
					<button 
						class="action-btn bind-btn" 
						:disabled="!isButlerUser"
						@click="goToDetail(searchResult._id)"
					>
						<text class="btn-text">绑定更新</text>
					</button>
					<button 
						class="action-btn task-btn" 
						@click="createTask"
					>
						<text class="btn-text">任务派单</text>
					</button>
					<button 
						class="action-btn share-btn" 
						:disabled="!canShowShareButton"
						open-type="share"
					>
						<text class="btn-text">名片分享</text>
					</button>
					<button 
						class="action-btn save-btn" 
						@click="saveCard"
					>
						<text class="btn-text">收藏</text>
					</button>
				</view>
			</view>
		</view>

		<!-- 待办列表 - 车管家用户始终显示 -->
		<view v-if="isButlerUser" class="todo-section">
			<view class="todo-container">
				<!-- 绑定列表标题 -->
				<view class="card-title-header">
					<text class="card-main-title">绑定列表</text>
				</view>
				
				<view v-if="todoList.length > 0" class="todo-list-content">
					<view 
						v-for="item in todoList" 
						:key="item._id" 
						class="todo-item"
						:class="{ 'urgent': item.isInTodoTime }"
						@click="viewTodoItem(item)"
					>
						<view class="todo-content">
							<text class="todo-plate">{{ item.plate_number }}</text>
						</view>
						<view class="todo-actions">
							<view class="todo-arrow">
								<text class="todo-arrow-text">查看</text>
								<uni-icons type="right" size="16" color="#B38B6D"></uni-icons>
							</view>
						</view>
					</view>
				</view>
				<view v-else class="empty-todo-content">
					<text class="empty-text">暂无绑定车辆</text>
					<text class="empty-desc">绑定车辆后，待办事项将在此显示</text>
				</view>
			</view>
		</view>

		<!-- 行驶证上传弹窗 -->
		<uni-popup ref="licenseUploadPopup" type="center">
			<view class="upload-popup">
				<view class="popup-header">
					<uni-icons type="camera" size="32" color="#2A7A72"></uni-icons>
					<text class="popup-title">上传行驶证正本</text>
				</view>
				<view class="popup-content">
					<view class="upload-tip">
						<text class="tip-text">请上传该车辆的行驶证正本照片</text>
						<text class="tip-sub">系统将自动识别车辆信息并创建三期名片</text>
					</view>
					<uni-file-picker 
						ref="licenseUpload"
						v-model="licenseFiles" 
						:image-styles="imageStyles"
						:sizeType="['compressed']" 
						return-type="object"
						@success="onLicenseUploadSuccess"
						@delete="onLicenseDelete"
						:disabled="isUploading">
						<view class="upload-area">
							<uni-icons type="image" size="40" color="#B38B6D"></uni-icons>
							<text class="upload-text">点击上传行驶证正本</text>
						</view>
					</uni-file-picker>
					<view v-if="isUploading" class="uploading-status">
						<view class="loading-spinner">
							<uni-icons type="spinner-cycle" size="20" color="#2A7A72"></uni-icons>
						</view>
						<text class="uploading-text">正在识别行驶证，请稍候...</text>
					</view>
				</view>
				<view class="popup-actions">
					<button class="cancel-btn" @click="cancelUpload" :disabled="isUploading">
						{{ isUploading ? '处理中...' : '取消' }}
					</button>
				</view>
			</view>
		</uni-popup>

		<!-- 收藏动画弹窗 -->
		<uni-popup ref="saveAnimationPopup" type="center">
			<view class="save-animation-popup">
				<view class="animation-content">
					<view class="save-icon">
						<uni-icons type="star-filled" size="48" color="#B38B6D"></uni-icons>
						<view class="icon-glow"></view>
					</view>
					<text class="save-text">请点击右上角 ··· 菜单</text>
					<text class="save-desc">将小程序添加到我的小程序</text>
					<view class="arrow-animation">
						<text class="arrow-text">⬆</text>
						<view class="arrow-pulse"></view>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 提示弹窗 -->
		<uni-popup ref="messagePopup" type="message">
			<uni-popup-message :type="messageType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
import {
	store
} from '@/uni_modules/uni-id-pages/common/store'

const db = uniCloud.databaseForJQL()

export default {
	data() {
		return {
			searchPlate: '',
			todoList: [],
			licenseFiles: [],
			messageType: 'success',
			messageText: '',
			currentSearchPlate: '',
			isUploading: false,
			imageStyles: {
				width: 400,
				height: 300
			},
			searchResult: {},
			butlerName: '',
			butlerMobile: '',
			isFirstLoad: true
		}
	},
	computed: {
		// 是否为车管家用户
		isButlerUser() {
			return this.uniIDHasRole('butler')
		},
		
		// 是否可以显示分享按钮
		canShowShareButton() {
			return this.searchResult._id && this.searchResult.butler_id
		},
		
		// 是否保险待办期内
		isInsuranceInTodoTime() {
			if (!this.searchResult._id || !this.searchResult.insurance_info || !this.searchResult.insurance_info.effective_date) return false
			
			const today = new Date()
			const effectiveDate = new Date(this.searchResult.insurance_info.effective_date)
			const todoStart = new Date(effectiveDate)
			todoStart.setFullYear(todoStart.getFullYear() + 1)
			todoStart.setDate(todoStart.getDate() - 28)
			
			const todoEnd = new Date(effectiveDate)
			todoEnd.setFullYear(todoEnd.getFullYear() + 1)
			
			return today >= todoStart && today <= todoEnd
		},

		// 是否保养待办期内
		isMaintenanceInTodoTime() {
			if (!this.searchResult._id || !this.searchResult.maintenance_info || !this.searchResult.maintenance_info.last_maintenance_date) return false
			
			const today = new Date()
			const lastDate = new Date(this.searchResult.maintenance_info.last_maintenance_date)
			const todoStart = new Date(lastDate)
			todoStart.setMonth(todoStart.getMonth() + 6)
			
			const todoEnd = new Date(lastDate)
			todoEnd.setMonth(todoEnd.getMonth() + 8)
			
			return today >= todoStart && today <= todoEnd
		},

		// 是否车检待办期内
		isInspectionInTodoTime() {
			if (!this.searchResult._id || !this.searchResult.inspection_info || !this.searchResult.inspection_info.next_inspection_date) return false
			
			const today = new Date()
			const nextDate = new Date(this.searchResult.inspection_info.next_inspection_date)
			const todoStart = new Date(nextDate)
			todoStart.setMonth(todoStart.getMonth() - 1)
			
			return today >= todoStart && today <= nextDate
		}
	},
	onLoad(options) {
		this.$nextTick(() => {
			this.initPage(options.plateNumber)
		})
	},
	onShow() {
		// 只有非首次加载时才刷新数据，避免重复加载
		if (!this.isFirstLoad && this.isButlerUser) {
			this.loadTodoList()
		}
		this.isFirstLoad = false
	},
	onShareAppMessage() {
		console.log('onShareAppMessage', this.searchResult)
		if (this.searchResult._id) {
			return {
				title: '三期名片：' + (this.searchResult.plate_number || ''),
				path: '/pages/yycw-car-archives/card?id=' + this.searchResult._id
			}
		}
		return {
			title: '三期名片',
			path: '/pages/yycw-car-archives/work'
		}
	},
	methods: {
		// 页面初始化
		async initPage(plateNumber) {
			// 非车管家用户，获取缓存中最后一次查询的车牌记录，自动进行一次三期名片搜索
			if (plateNumber) {
				this.searchPlate = plateNumber
				await this.onSearch()
			} else if (!this.isButlerUser) {
				const lastSearchPlate = this.getLastSearchPlate()
				if (lastSearchPlate) {
					this.searchPlate = lastSearchPlate
					await this.onSearch()
				}
			} 
			if (this.isButlerUser) {
				// 车管家用户加载待办列表
				this.loadTodoList()
			}
		},
		
		// 获取最后一次搜索的车牌
		getLastSearchPlate() {
			try {
				return uni.getStorageSync('last_search_plate')
			} catch (e) {
				return ''
			}
		},
		
		// 保存搜索记录
		saveSearchPlate(plate) {
			try {
				uni.setStorageSync('last_search_plate', plate)
			} catch (e) {
				console.error('保存搜索记录失败:', e)
			}
		},
		
		// 搜索车牌号
		async onSearch() {
			if (!this.searchPlate.trim()) {
				this.showMessage('error', '请输入车牌号码')
				return
			}
			
			this.currentSearchPlate = this.searchPlate.trim()
			this.saveSearchPlate(this.currentSearchPlate)
			
			try {
				uni.showLoading({ title: '搜索中...' })
				
				const res = await db.collection('yycw-car-archives')
					.where(`plate_number == "${this.currentSearchPlate}"`)
					.get()

				if (res.data.length === 0) {
					// 未查到相应三期名片
					if (this.isButlerUser) {
						// 车管家用户，弹窗上传行驶证
						this.$nextTick(() => {
							if (this.$refs.licenseUploadPopup) {
								this.$refs.licenseUploadPopup.open()
							}
						})
					} else {
						// 非车管家用户，显示空的三期名片
						this.showEmptyCard()
					}
				} else {
					const card = res.data[0]
					await this.handleSearchResult(card)
				}
			} catch (error) {
				console.error('搜索失败:', error)
				this.showMessage('error', '搜索失败，请重试')
			} finally {
				uni.hideLoading()
			}
		},

		// 显示空的三期名片（用于非车管家用户）
		showEmptyCard() {
			this.searchResult = {
				_id: '',
				plate_number: this.currentSearchPlate,
				license_info: {},
				insurance_info: {},
				maintenance_info: {},
				inspection_info: {},
				butler_id: ''
			}
			this.butlerName = ''
			this.butlerMobile = ''
		},

		// 处理搜索结果
		async handleSearchResult(card) {
			if (!card.butler_id) {
				// 未绑定车管家
				if (this.isButlerUser) {
					// 车管家用户，跳转详情页
					this.goToDetail(card._id)
				} else {
					// 非车管家用户，显示空的三期名片
					this.showEmptyCard()
				}
			} else {
				// 已绑定车管家
				this.searchResult = card
				// 获取车管家信息
				await this.getButlerInfo(card.butler_id)
			}
		},

		// 获取车管家信息
		async getButlerInfo(butlerId) {
			try {
				const res = await db.collection('uni-id-users').doc(butlerId).field('nickname,mobile').get()
				if (res.data.length > 0) {
					this.butlerName = res.data[0].nickname || '未设置昵称'
					this.butlerMobile = res.data[0].mobile || ''
				}
			} catch (err) {
				console.error('获取车管家信息失败:', err)
				this.butlerName = '获取失败'
				this.butlerMobile = ''
			}
		},

		// 拨打电话
		callButler() {
			if (!this.butlerMobile) return
			uni.makePhoneCall({
				phoneNumber: this.butlerMobile
			})
		},

		// 选择车管家
		selectButler() {
			// 这里可以跳转到选择车管家的页面，或者显示提示
			uni.showModal({
				title: '提示',
				content: '请联系客服为您分配专属车管家',
				showCancel: false
			})
		},

		// 格式化日期
		formatDate(date) {
			if (!date) return '--'
			const d = new Date(date)
			const year = d.getFullYear()
			const month = String(d.getMonth() + 1).padStart(2, '0')
			const day = String(d.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},

		// 获取保险待办期范围
		getInsuranceTodoRange() {
			if (!this.searchResult || !this.searchResult.insurance_info || !this.searchResult.insurance_info.effective_date) return '暂无数据'
			
			const effectiveDate = new Date(this.searchResult.insurance_info.effective_date)
			const startDate = new Date(effectiveDate)
			startDate.setFullYear(startDate.getFullYear() + 1)
			startDate.setDate(startDate.getDate() - 28)
			
			const endDate = new Date(effectiveDate)
			endDate.setFullYear(endDate.getFullYear() + 1)
			
			return `${this.formatDate(startDate)} - ${this.formatDate(endDate)}`
		},

		// 获取保养待办期范围
		getMaintenanceTodoRange() {
			if (!this.searchResult || !this.searchResult.maintenance_info || !this.searchResult.maintenance_info.last_maintenance_date) return '暂无数据'
			
			const lastDate = new Date(this.searchResult.maintenance_info.last_maintenance_date)
			const startDate = new Date(lastDate)
			startDate.setMonth(startDate.getMonth() + 6)
			
			const endDate = new Date(lastDate)
			endDate.setMonth(endDate.getMonth() + 8)
			
			return `${this.formatDate(startDate)} - ${this.formatDate(endDate)}`
		},

		// 获取车检待办期范围
		getInspectionTodoRange() {
			if (!this.searchResult || !this.searchResult.inspection_info || !this.searchResult.inspection_info.next_inspection_date) return '暂无数据'
			
			const nextDate = new Date(this.searchResult.inspection_info.next_inspection_date)
			const startDate = new Date(nextDate)
			startDate.setMonth(startDate.getMonth() - 1)
			
			return `${this.formatDate(startDate)} - ${this.formatDate(nextDate)}`
		},

		// 跳转到详情页
		goToDetail(cardId) {
			// 如果是从待办列表点击进入，直接跳转
			if (cardId) {
				uni.navigateTo({
					url: `/pages/yycw-car-archives/detail?id=${cardId}`
				})
				return
			}
			
			// 检查是否有搜索结果（使用_id判断）
			if (!this.searchResult._id) {
				// 没有搜索结果ID，检查是否搜索过但没有创建三期名片
				if (this.isButlerUser) {
					// 车管家用户弹窗上传行驶证正本
					this.$nextTick(() => {
						if (this.$refs.licenseUploadPopup) {
							this.$refs.licenseUploadPopup.open()
						}
					})
				} else {
					this.showMessage('error', '请联系车管家创建三期名片')
				}
				return
			}
			
			// 有三期名片ID，检查绑定状态
			const butlerId = this.searchResult.butler_id
			const bindStatus = this.searchResult.butler_bind_status
			const expireDate = this.searchResult.butler_expire_date
			const currentUserId = store.userInfo && store.userInfo._id
			
			// 检查是否已绑定且在有效期内
			if (butlerId && bindStatus === 1) {
				// 检查绑定是否过期
				const isExpired = expireDate && new Date() > new Date(expireDate)
				
				if (!isExpired) {
					// 绑定有效，检查车管家是否为当前用户
					if (butlerId !== currentUserId) {
						this.showMessage('error', '该车辆已被其他车管家绑定，无法操作')
						return
					}
				}
			}
			
			// 其他情况，携带三期名片ID跳转详情页
			uni.navigateTo({
				url: `/pages/yycw-car-archives/detail?id=${this.searchResult._id}`
			})
		},

		// 任务派单
		createTask() {
			if (!this.searchResult) return
			
			// 使用绑定的车管家ID，如果没有则使用当前用户ID
			const butlerId = this.searchResult.butler_id || (this.isButlerUser ? (store.userInfo && store.userInfo._id) : '') || ''
			
			// 跳转到任务派单页面
			uni.navigateTo({
				url: `/pages/yycw_car_service_order/add?plate_number=${this.searchResult.plate_number}&archives_id=${this.searchResult._id || ''}&butler_id=${butlerId}`
			})
		},

		// 保存功能
		saveCard() {
			if (!this.searchResult.butler_id) {
				this.showMessage('error', '该车辆尚未绑定车管家，请先绑定车管家后再使用此功能')
				return
			}
			
			// 显示收藏动画
			this.$refs.saveAnimationPopup.open()
			
			// 5秒后自动关闭
			setTimeout(() => {
				this.$refs.saveAnimationPopup.close()
			}, 5000)
		},

		// 行驶证上传成功回调
		async onLicenseUploadSuccess(event) {
			console.log('行驶证上传成功:', event)
			const licenseFiles = event.tempFiles || []
			if (!licenseFiles.length || !licenseFiles[0].url) {
				this.showMessage('error', '行驶证文件无效，请重新上传')
				this.$refs.licenseUpload.clearFiles()
				return
			}

			try {
				this.isUploading = true
				uni.showLoading({ title: '识别行驶证中...' })
				
				// 调用云函数识别行驶证并创建三期名片
				const result = await uniCloud.callFunction({
					name: 'yycw-car-archives',
					data: {
						action: 'recognizeVehicleLicenseByFace',
						params: {
							url: licenseFiles[0].url,
							butlerId: store.userInfo._id,
							orderId: '',
							extname: licenseFiles[0].extname,
							name: licenseFiles[0].name 
						}
					}
				})
                
				uni.hideLoading()
				
				if (result.result.errCode) {
					this.showMessage('error', result.result.errMsg || '识别失败，请重试')
				} else {
					this.$refs.licenseUploadPopup.close()
					this.licenseFiles = []
					this.showMessage('success', '识别成功，正在跳转...')
					
					// 跳转到详情页
					setTimeout(() => {
						this.goToDetail(result.result.id)
					}, 500)
				}

			} catch (error) {
				uni.hideLoading()
				console.error('识别失败:', error)
				this.showMessage('error', '识别失败，请重试')
			} finally {
				this.isUploading = false
			}
		},

		// 行驶证删除回调
		onLicenseDelete(event) {
			console.log('行驶证删除:', event)
			this.isUploading = false
		},

		// 取消上传
		cancelUpload() {
			this.$refs.licenseUploadPopup.close()
			this.licenseFiles = []
			this.isUploading = false
		},

		// 加载待办列表
		async loadTodoList() {
			if (!this.isButlerUser) return
			
			try {
				const currentTime = new Date()
				const res = await db.collection('yycw-car-archives')
					.where(
					`butler_id == "${store.userInfo._id}" && butler_bind_status == 1 && butler_expire_date > ${currentTime.getTime()}`)
					.field('_id, plate_number, insurance_info, maintenance_info, inspection_info, butler_bind_date, butler_expire_date')
					.get()

				// 计算待办信息并排序
				this.todoList = res.data
					.map(item => {
						const todoInfo = this.calculateTodoInfo(item)
						return {
							...item,
							...todoInfo
						}
					})
					.sort((a, b) => {
						// 按可办期开始时间升序排序
						const aStartTime = a.earliestTodoStartTime || Number.MAX_SAFE_INTEGER
						const bStartTime = b.earliestTodoStartTime || Number.MAX_SAFE_INTEGER
						return aStartTime - bStartTime
					})

			} catch (error) {
				console.error('加载待办列表失败:', error)
			}
		},

		// 计算待办信息
		calculateTodoInfo(card) {
			const today = new Date()
			let maxOverdueDays = 0
			let todoType = ''
			let hasTodo = false
			let earliestTodoStartTime = Number.MAX_SAFE_INTEGER
			let isInTodoTime = false

			// 检查保险待办
			if (card.insurance_info?.effective_date) {
				const effectiveDate = new Date(card.insurance_info.effective_date)
				const todoStartDate = new Date(effectiveDate)
				todoStartDate.setFullYear(todoStartDate.getFullYear() + 1)
				todoStartDate.setDate(todoStartDate.getDate() - 28)
				
				const todoStartTime = todoStartDate.getTime()
				if (todoStartTime < earliestTodoStartTime) {
					earliestTodoStartTime = todoStartTime
				}
				
				if (today >= todoStartDate) {
					hasTodo = true
					isInTodoTime = true
					const overdueDays = Math.floor((today - todoStartDate) / (1000 * 60 * 60 * 24))
					if (overdueDays > maxOverdueDays) {
						maxOverdueDays = overdueDays
						todoType = '保险服务'
					}
				}
			}

			// 检查保养待办
			if (card.maintenance_info?.last_maintenance_date) {
				const lastDate = new Date(card.maintenance_info.last_maintenance_date)
				const todoStartDate = new Date(lastDate)
				todoStartDate.setMonth(todoStartDate.getMonth() + 6)
				
				const todoStartTime = todoStartDate.getTime()
				if (todoStartTime < earliestTodoStartTime) {
					earliestTodoStartTime = todoStartTime
				}
				
				if (today >= todoStartDate) {
					hasTodo = true
					isInTodoTime = true
					const overdueDays = Math.floor((today - todoStartDate) / (1000 * 60 * 60 * 24))
					if (overdueDays > maxOverdueDays) {
						maxOverdueDays = overdueDays
						todoType = '保养服务'
					}
				}
			}

			// 检查车检待办
			if (card.inspection_info?.next_inspection_date) {
				const nextDate = new Date(card.inspection_info.next_inspection_date)
				const todoStartDate = new Date(nextDate)
				todoStartDate.setMonth(todoStartDate.getMonth() - 1)
				
				const todoStartTime = todoStartDate.getTime()
				if (todoStartTime < earliestTodoStartTime) {
					earliestTodoStartTime = todoStartTime
				}
				
				if (today >= todoStartDate) {
					hasTodo = true
					isInTodoTime = true
					const overdueDays = Math.floor((today - todoStartDate) / (1000 * 60 * 60 * 24))
					if (overdueDays > maxOverdueDays) {
						maxOverdueDays = overdueDays
						todoType = '车检服务'
					}
				}
			}

			return {
				hasTodo,
				overdueDays: maxOverdueDays,
				todoType,
				earliestTodoStartTime: earliestTodoStartTime === Number.MAX_SAFE_INTEGER ? null : earliestTodoStartTime,
				isInTodoTime
			}
		},

		// 点击查看按钮，直接赋值数据到查询结果
		viewTodoItem(item) {
			try {
				// 直接使用传入的item数据赋值给搜索结果
				this.searchResult = item
				this.searchPlate = item.plate_number
				this.currentSearchPlate = item.plate_number
				
				// 获取车管家信息
				if (item.butler_id) {
					this.getButlerInfo(item.butler_id)
				} else {
					this.butlerName = ''
					this.butlerMobile = ''
				}
				
				// 滚动到三期名片区域
				this.$nextTick(() => {
					// 使用uni-app的页面滚动方法
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 300
					})
				})
				
				// this.showMessage('success', '查看成功')
			} catch (error) {
				console.error('查看失败:', error)
				this.showMessage('error', '查看失败，请重试')
			}
		},

		// 显示消息
		showMessage(type, text) {
			this.messageType = type
			this.messageText = text
			this.$refs.messagePopup.open()
		},
		
		// 重写返回按钮点击事件
		onBackPress() {
			// 返回首页
			uni.switchTab({
				url: '/pages/index/index'
			})
			return true // 阻止默认返回行为
		},
	}
}
</script>

<style lang="scss" scoped>
/* 配色变量定义 */
$primary-color: #2A7A72;
$accent-jump: #4ECDC4;
$accent-stable: #245E5A;
$steel-gray: #424B54;
$parchment-white: #F5F0E6;
$bronze-gold: #B38B6D;

.container {
	padding: 20rpx;
	background: $primary-color;
	min-height: 100vh;
	
	> .uni-search-bar {
		margin: 0 12rpx;
	}
}

.card-section {
	margin-top: 30rpx;
	margin-bottom: 30rpx;
}

.card-container {
	background: $parchment-white;
	border-radius: 20rpx;
	padding: 32rpx;
	margin: 0 12rpx;
	box-shadow: 0 8rpx 32rpx rgba(42, 122, 114, 0.12);
	border: 1rpx solid rgba(42, 122, 114, 0.08);
	position: relative;
	overflow: hidden;
	
	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 4rpx;
		background: linear-gradient(90deg, $primary-color 0%, $accent-jump 100%);
	}
}

.card-title-header {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 24rpx;
}

.card-main-title {
	font-size: 36rpx;
	font-weight: 600;
	color: $primary-color;
	margin-top: 6rpx;
}

.service-dates-rows {
	margin-bottom: 24rpx;
	background: $parchment-white;
	border-radius: 12rpx;
	padding: 20rpx;
	
	.date-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12rpx 0;
		border-bottom: 1rpx solid rgba(42, 122, 114, 0.1);
		
		&:last-child {
			border-bottom: none;
		}
		
		.date-type-tag {
			font-size: 28rpx;
			font-weight: 600;
			padding: 6rpx 12rpx;
			border-radius: 12rpx;
			color: #FFFFFF;
			min-width: 120rpx;
			text-align: center;
			
			&.insurance {
				background: linear-gradient(135deg, $primary-color 0%, $accent-stable 100%);
			}
			
			&.maintenance {
				background: linear-gradient(135deg, $accent-jump 0%, $primary-color 100%);
			}
			
			&.inspection {
				background: linear-gradient(135deg, $bronze-gold 0%, #A67C52 100%);
			}
			
			&.butler {
				background: linear-gradient(135deg, $steel-gray 0%, #2F3640 100%);
			}
		}
		
		.date-value {
			font-size: 28rpx;
			color: #424B54;
			text-align: right;
			flex: 1;
			margin-left: 16rpx;
			
			&.active {
				color: $primary-color;
				font-weight: 600;
			}
		}
		
		.butler-info-content {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			flex: 1;
			margin-left: 16rpx;
			text-align: right;
			
			.butler-right-section {
				display: flex;
				align-items: center;
				gap: 8rpx;
				margin-left: auto;
				
				.butler-name {
					font-size: 28rpx;
					color: $primary-color;
					font-weight: 600;
				}
				
				.contact-btn-compact,
				.select-butler-btn-compact {
					background: $primary-color;
					color: #FFFFFF;
					border: none;
					border-radius: 12rpx;
					padding: 4rpx 8rpx;
					font-size: 24rpx;
					font-weight: 600;
					display: flex;
					align-items: center;
					justify-content: center;
					gap: 4rpx;
					text-align: center;
					
					&:active {
						background: $accent-stable;
					}
					
					.contact-text {
						color: #FFFFFF;
					}
				}
				
				.select-butler-btn-compact {
					background: linear-gradient(135deg, $bronze-gold 0%, #A67C52 100%);
					font-size: 24rpx;
					
					&:active {
						background: linear-gradient(135deg, #A67C52 0%, $bronze-gold 100%);
					}
				}
			}
		}
	}
}

.action-buttons-row {
	display: flex;
	justify-content: space-between;
	gap: 12rpx;
	
	.action-btn {
		flex: 1;
		border: none;
		border-radius: 10rpx;
		padding: 16rpx 8rpx;
		font-size: 28rpx;
		font-weight: 600;
		text-align: center;
		transition: all 0.3s ease;
		box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
		
		.btn-text {
			color: #FFFFFF;
		}
		
		&:disabled {
			opacity: 1;
			background: #E0E0E0 !important;
			box-shadow: none;
			
			.btn-text {
				color: #424B54;
			}
			
			&:active {
				transform: none;
				box-shadow: none;
			}
		}
		
		&.bind-btn {
			background: linear-gradient(135deg, $primary-color 0%, $accent-stable 100%);
			
			&:active:not(:disabled) {
				transform: translateY(1rpx);
				box-shadow: 0 1rpx 4rpx rgba(42, 122, 114, 0.3);
			}
		}
		
		&.task-btn {
			background: linear-gradient(135deg, $accent-jump 0%, $primary-color 100%);
			
			&:active:not(:disabled) {
				transform: translateY(1rpx);
				box-shadow: 0 1rpx 4rpx rgba(78, 205, 196, 0.3);
			}
		}
		
		&.share-btn {
			background: linear-gradient(135deg, $bronze-gold 0%, #A67C52 100%);
			
			&:active:not(:disabled) {
				transform: translateY(1rpx);
				box-shadow: 0 1rpx 4rpx rgba(179, 139, 109, 0.3);
			}
		}
		
		&.save-btn {
			background: linear-gradient(135deg, $steel-gray 0%, #2F3640 100%);
			
			&:active:not(:disabled) {
				transform: translateY(1rpx);
				box-shadow: 0 1rpx 4rpx rgba(66, 75, 84, 0.3);
			}
		}
	}
}

.todo-section {
	margin-bottom: 30rpx;
}

.todo-container {
	background: $parchment-white;
	border-radius: 20rpx;
	padding: 32rpx;
	margin: 0 12rpx;
	box-shadow: 0 8rpx 32rpx rgba(42, 122, 114, 0.12);
	border: 1rpx solid rgba(42, 122, 114, 0.08);
	position: relative;
	overflow: hidden;
	
	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 4rpx;
		background: linear-gradient(90deg, $primary-color 0%, $accent-jump 100%);
	}
}

.todo-list-content {
	margin-top: 24rpx;
	
	.todo-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 0;
		border-bottom: 1rpx solid rgba(42, 122, 114, 0.1);
		transition: background 0.3s ease;
		
		&:last-child {
			border-bottom: none;
		}
		
		&:active {
			background: rgba(42, 122, 114, 0.05);
			border-radius: 8rpx;
			margin: 0 -8rpx;
			padding: 24rpx 8rpx;
		}
		
		// 重点色样式 - 处于可办期的项目
		&.urgent {
			background: linear-gradient(135deg, rgba(255, 107, 107, 0.1) 0%, rgba(255, 82, 82, 0.05) 100%);
			border-left: 4rpx solid #FF6B6B;
			border-radius: 8rpx;
			margin: 0 -8rpx;
			padding: 24rpx 8rpx;
			
			.todo-content {
				.todo-plate {
					color: #FF6B6B;
					font-weight: 700;
				}
			}
			
			.todo-actions {
				.todo-arrow {
					.todo-arrow-text {
						color: #FF6B6B;
						font-weight: 600;
					}
					
					uni-icons {
						color: #FF6B6B !important;
					}
				}
			}
			
			&:active {
				background: linear-gradient(135deg, rgba(255, 107, 107, 0.2) 0%, rgba(255, 82, 82, 0.1) 100%);
			}
		}
		
		.todo-content {
			flex: 1;
			
			.todo-plate {
				font-size: 30rpx;
				font-weight: 600;
				color: $steel-gray;
				display: block;
			}
		}
		
		.todo-actions {
			display: flex;
			align-items: center;
			gap: 12rpx;
			
			.todo-arrow {
				display: flex;
				align-items: center;
				gap: 8rpx;
				
				.todo-arrow-text {
					font-size: 22rpx;
					color: #999999;
					font-weight: 500;
				}
			}
		}
	}
}

.empty-todo-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 40rpx 20rpx;
	margin-top: 24rpx;
	
	.empty-icon {
		margin-bottom: 24rpx;
	}
	
	.empty-text {
		font-size: 32rpx;
		font-weight: 600;
		color: $steel-gray;
		margin-bottom: 12rpx;
	}
	
	.empty-desc {
		font-size: 26rpx;
		color: #999999;
		text-align: center;
	}
}

.upload-popup {
	background: #FFFFFF;
	border-radius: 24rpx;
	padding: 40rpx;
	width: 640rpx;
	box-shadow: 0 12rpx 48rpx rgba(42, 122, 114, 0.15);
	
	.popup-header {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 32rpx;
		
		.popup-title {
			margin-top: 16rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: $steel-gray;
		}
	}
	
	.popup-content {
		margin-bottom: 32rpx;
		
		.upload-tip {
			text-align: center;
			margin-bottom: 24rpx;
			
			.tip-text {
				display: block;
				font-size: 28rpx;
				color: $steel-gray;
				font-weight: 500;
				margin-bottom: 8rpx;
			}
			
			.tip-sub {
				display: block;
				font-size: 24rpx;
				color: #999999;
				line-height: 1.4;
			}
		}
		
		.upload-area {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60rpx 20rpx;
			border: 2rpx dashed $bronze-gold;
			border-radius: 16rpx;
			background: rgba(179, 139, 109, 0.04);
			margin: 20rpx 0;
			
			.upload-text {
				margin-top: 16rpx;
				font-size: 26rpx;
				color: $bronze-gold;
				font-weight: 500;
			}
		}
		
		.uploading-status {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 24rpx;
			padding: 24rpx;
			background: $parchment-white;
			border-radius: 12rpx;
			gap: 12rpx;
			
			.loading-spinner {
				animation: spin 1s linear infinite;
			}
			
			.uploading-text {
				color: $steel-gray;
				font-size: 26rpx;
				font-weight: 500;
			}
		}
	}
	
	.popup-actions {
		.cancel-btn {
			width: 100%;
			padding: 24rpx;
			border-radius: 12rpx;
			font-size: 28rpx;
			font-weight: 600;
			border: 2rpx solid $bronze-gold;
			background: #FFFFFF;
			color: $bronze-gold;
			
			&:disabled {
				background: #E0E0E0;
				color: #999999;
				border-color: #CCCCCC;
			}
			
			&:active:not(:disabled) {
				background: $bronze-gold;
				color: #FFFFFF;
			}
		}
	}
}

.save-animation-popup {
	background: #FFFFFF;
	border-radius: 24rpx;
	padding: 60rpx 40rpx;
	width: 520rpx;
	text-align: center;
	box-shadow: 0 12rpx 48rpx rgba(42, 122, 114, 0.15);
	
	.animation-content {
		.save-icon {
			position: relative;
			margin-bottom: 24rpx;
			display: inline-block;
			
			.icon-glow {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 80rpx;
				height: 80rpx;
				background: radial-gradient(circle, rgba(179, 139, 109, 0.3) 0%, transparent 70%);
				border-radius: 50%;
				animation: glow 2s ease-in-out infinite;
			}
		}
		
		.save-text {
			display: block;
			font-size: 30rpx;
			color: $steel-gray;
			font-weight: 600;
			margin-bottom: 12rpx;
		}
		
		.save-desc {
			display: block;
			font-size: 26rpx;
			color: #999999;
			margin-bottom: 32rpx;
			line-height: 1.4;
		}
		
		.arrow-animation {
			position: relative;
			
			.arrow-text {
				font-size: 48rpx;
				color: $primary-color;
				animation: bounce 1.2s infinite;
				display: inline-block;
			}
			
			.arrow-pulse {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 60rpx;
				height: 60rpx;
				border: 2rpx solid $primary-color;
				border-radius: 50%;
				animation: arrow-pulse 2s infinite;
			}
		}
	}
}

/* 动画定义 */
@keyframes bounce {
	0%, 20%, 50%, 80%, 100% {
		transform: translateY(0);
	}
	40% {
		transform: translateY(-16rpx);
	}
	60% {
		transform: translateY(-8rpx);
	}
}

@keyframes glow {
	0%, 100% {
		opacity: 0.5;
		transform: translate(-50%, -50%) scale(1);
	}
	50% {
		opacity: 0.8;
		transform: translate(-50%, -50%) scale(1.2);
	}
}

@keyframes arrow-pulse {
	0% {
		opacity: 1;
		transform: translate(-50%, -50%) scale(0.8);
	}
	100% {
		opacity: 0;
		transform: translate(-50%, -50%) scale(1.5);
	}
}

@keyframes spin {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}
</style>

